package com.mzpai.api.config;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mzpai.product.model.OperateLog;
import com.mzpai.product.service.OperateLogService;
import com.mzpai.util.ApplicationContextUtils;
import com.mzpai.util.StringUtils;



@Configuration
public class LogInterceptor  implements HandlerInterceptor{
	private Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
	private OperateLogService operateLogService = null;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (request.getRequestURI().contains("/api/login")) {
			return true;
		}
		String uri = request.getRequestURI();
		operateLogService = ApplicationContextUtils.getBean(OperateLogService.class);
		OperateLog operateLog = new OperateLog();
		operateLog.setUrl(uri);

		StringBuilder sb = new StringBuilder();
		String param = null;
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
			sb.append(entry.getKey()).append("=").append(Arrays.toString(entry.getValue())).append("&");
		}
		param = StringUtils.removeEndStr(sb.toString(), "&");
		operateLog.setParams(param);
		logger.info(",,uri={},,msg1={}",uri,"请求开始");
		operateLog.setOperateTime(new Date());
		
		Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
            	//logger.info("msg1=请求参数信息={}", JSON.toJSON(operateLog));
            	try{
            	operateLogService.save(operateLog);
            	}catch(Exception e) {logger.info("", e);}
            }
        });
        thread.start();

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String uri = request.getRequestURI();
		logger.info(",,uri={},,msg1={}",uri,"请求结束");
	}


	public static class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
		public MyHttpServletRequestWrapper(HttpServletRequest request) {
			super(request);
		}
	}

}
